package com.bosc.modeling.controller;

import com.bosc.modeling.common.BaseController;
import com.bosc.modeling.common.BaseEvaluator;
import com.bosc.modeling.common.ResponseFactory;
import com.bosc.modeling.pojo.gen.*;
import com.bosc.modeling.service.CompetitionService;
import com.bosc.modeling.service.ResultService;
import com.bosc.modeling.service.TeamService;
import com.bosc.modeling.utils.FileHandleUtil;
import com.bosc.modeling.utils.SpringUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * @author yuanyj
 * @version 1.0
 * @date 2019/11/25 15:02
 * @description
 */
@RestController
public class ResultController extends BaseController {
    @Autowired
    CompetitionService competitionService;
    @Autowired
    TeamService teamService;
    @Autowired
    ResultService resultService;
    @Value("${file.uploadFolder}")
    private String uploadFolder;
    @RequestMapping(value = "result_upload", method = RequestMethod.POST)
    Object resultUplpad(@RequestParam("file") MultipartFile file, @RequestParam("competition_id") String competitionId,@RequestParam("user_id") String userId) throws Exception {
        log.info("resultUplpad:"+file.getOriginalFilename());
        try {
            CompetitionEntity competition = competitionService.getCompetitionById(competitionId).get(0);
            short state = competition.getState();
            if (state == 0){
                return ResponseFactory.failureResponse(null,"比赛未开始");
            }
            if (state == 3){
                return ResponseFactory.failureResponse(null,"比赛已结束");
            }
            String teamId = null;
            String teamName = null;
            List<EnrollEntity> enrolls = teamService.getEnrollByCompetitionId(competitionId);
            for (EnrollEntity enroll:enrolls) {
                List<TeamEntity> teams = teamService.getTeamByUserId(enroll.getTeamId(),userId);
                if (teams.size() > 0){
                    teamId = teams.get(0).getTeamId();
                    teamName =teams.get(0).getTeamName();
                    break;
                }
            }
            if (teamId == null){
                return ResponseFactory.failureResponse(null,"查询不到团队");
            }
            InputStream is = file.getInputStream();
            InputStreamReader bis = new InputStreamReader(is);
            BufferedReader reader = new BufferedReader(bis);
            List<Double> result = new ArrayList<Double>();
            String line;
            while ((line=reader.readLine()) != null){
                result.add(Double.valueOf(line.split(" ")[1]));
            }
            double score = 0;
            if (state == 1){
                String[] urls = competition.getTestDataUrlA().split("/");
                int len = urls.length;
                String filePath = uploadFolder+urls[len-2]+"/"+urls[len-1];
                reader = new BufferedReader(new InputStreamReader(new FileInputStream(filePath)));
                List<Double> testRes = new ArrayList<Double>();
                while ((line=reader.readLine()) != null){
                    testRes.add(Double.valueOf(line.split(" ")[1]));
                }
                BaseEvaluator evaluator = SpringUtil.getBean(competition.getEvaluation());
                score = evaluator.evaluate(result,testRes);
                ScoreAEntity entity = new ScoreAEntity();
                entity.setCompetitionId(competitionId);
                entity.setScore(score);
                entity.setTeamId(teamId);
                entity.setTeamName(teamName);
                entity.setUserId(userId);
                entity.setTime(new Date());
                resultService.insertScoreA(entity);
            }
            if (state == 2){
                String[] urls = competition.getTestDataUrlB().split("/");
                int len = urls.length;
                String filePath = uploadFolder+urls[len-2]+"/"+urls[len-1];
                reader = new BufferedReader(new InputStreamReader(new FileInputStream(filePath)));
                List<Double> testRes = new ArrayList<Double>();
                while ((line=reader.readLine()) != null){
                    testRes.add(Double.valueOf(line.split(" ")[1]));
                }
//                double score_A = resultService.getHighestScoreA(competitionId,teamId);
                BaseEvaluator evaluator = SpringUtil.getBean(competition.getEvaluation());
                double score_B = evaluator.evaluate(result,testRes);
                score = score_B;
                ScoreBEntity entity = new ScoreBEntity();
                entity.setCompetitionId(competitionId);
                entity.setScore(score);
                entity.setTeamId(teamId);
                entity.setTeamName(teamName);
                entity.setUserId(userId);
                entity.setTime(new Date());
                resultService.insertScoreB(entity);
            }
            HashMap data = new HashMap();
            data.put("score",score);
            return ResponseFactory.successResponse(data);
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }
    @RequestMapping(value = "score_list", method = RequestMethod.GET)
    Object scoreList(@RequestParam("competition_id") String competitionId,@RequestParam("user_id") String userId,@RequestParam("page") int page, @RequestParam("limit") int limit) throws Exception {
        log.info("scoreList:page="+page+",limit="+limit);
        try {
            CompetitionEntity competition = competitionService.getCompetitionById(competitionId).get(0);
            short state = competition.getState();
            String teamId = null;
            List<EnrollEntity> enrolls = teamService.getEnrollByCompetitionId(competitionId);
            for (EnrollEntity enroll:enrolls) {
                List<TeamEntity> teams = teamService.getTeamByUserId(enroll.getTeamId(),userId);
                if (teams.size() > 0){
                    teamId = enroll.getTeamId();
                    break;
                }
            }
            if (teamId == null){
                HashMap res = new HashMap();
                res.put("status",0);
                res.put("message","");
                res.put("total",0);
                res.put("data", null);
                return res;
            }
            if (state == 1){
                PageHelper.startPage(page, limit);
                List<ScoreAEntity> list = resultService.getScoreAList(competitionId,teamId,userId);
                PageInfo<ScoreAEntity> pageInfo = new PageInfo<ScoreAEntity>(list);
                long count = pageInfo.getTotal();
                List data = pageInfo.getList();
                HashMap res = new HashMap();
                res.put("status",0);
                res.put("message","");
                res.put("total",count);
                res.put("data", data);
                return res;
            }
            if (state == 2 || state == 3){
                PageHelper.startPage(page, limit);
                List<Object> list = resultService.getScoreList(competitionId,teamId,userId);
                PageInfo<Object> pageInfo = new PageInfo<Object>(list);
                long count = pageInfo.getTotal();
                List data = pageInfo.getList();
                HashMap res = new HashMap();
                res.put("status",0);
                res.put("message","");
                res.put("total",count);
                res.put("data", data);
                return res;
            }
            HashMap res = new HashMap();
            res.put("status",0);
            res.put("message","");
            res.put("total",0);
            res.put("data", null);
            return res;
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }
    @RequestMapping(value = "/sort_list",method = RequestMethod.GET)
    public Object sortList(@RequestParam("competition_id") String competitionId,@RequestParam("page") int page, @RequestParam("limit") int limit){
        log.info("sortList:page="+page+",limit="+limit);
        try {
            CompetitionEntity competition = competitionService.getCompetitionById(competitionId).get(0);
            short state = competition.getState();
            PageHelper.startPage(page, limit);
            List<ScoreAEntity> list = resultService.getSortList(competition,state);
            PageInfo<ScoreAEntity> pageInfo = new PageInfo<ScoreAEntity>(list);
            long count = pageInfo.getTotal();
            List data = pageInfo.getList();
            HashMap res = new HashMap();
            res.put("status",0);
            res.put("message","");
            res.put("total",count);
            res.put("data", data);
            return res;
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }
}
